<?php

/**
 * 新版本,每个咨询类型. 单独定价
 */

namespace app\v6\controller;

use think\Db;
use think\Exception;
use app\service\paipan;
use think\cache\driver\Redis;
use think\facade\Lang;

class Index
{
    /**
     * 分类下包含的预测问题
     *
     * @return void
     */
    public function getQuestionList()
    {
        $res = ['code' => 1, 'data' => [], 'msg' => ''];
        try {
            $cid3 = input('cid3', 0);
            $data = Db::name('question_new')->field('*')->where(['cid3' => $cid3])->select();
            foreach ($data  as $key => $value) {
                $value['prompts'] = explode(',', $value['prompts']);
                $value['questions'] = explode(',', $value['questions']);
                $res['data'][] = $value;
            };
            $res['code'] = 0;
            return json($res);
        } catch (\Throwable $th) {
            $res['code'] = 1;
            $res['msg'] = $th->getMessage();
            return json($res);
        }
    }

    /**
     * 最新版本AI预测 
     */
    public function latestPersonPredict()
    {
        $res = ['code' => 1, 'data' => [], 'msg' => ''];
        try {
            $user_phone = input('user_phone', '');
            if (empty($user_phone)) {
                throw new Exception("手机号为必填参数", 1);
            }
            //记录时间是否应该付费  0 付费 1免费(默认支付)
            $time_pay = input('time_pay', 0);
            $question_id = input('question_id', 0);
            $data = Db::name('question_new')->field('*')->where(['id' => $question_id])->find();
            if (empty($data)) {
                throw new Exception(Lang::get('error_question_id'), 1);
            }
            $type = $data['answer_type'];
            # 查询当前用户, 在当前类型下,是否有可用套餐
            # 用户无可用套餐, 不允许咨询
            $memField = 'id,once_nums,month_day,works_once_nums,works_month_nums,emotion_once_nums,emotion_month_nums,pr_once_nums,pr_month_nums,group_once_nums,group_month_nums';
            $userComboInfo = Db::name('member')->field($memField)->where(['phone' => $user_phone])->find();
            if (empty($userComboInfo)) {
                throw new Exception(Lang::get('user_no_available_combo'), 1);
            }
            # 根据每个咨询
            switch ($type) {
                case 1:
                    if ($userComboInfo['once_nums'] <= 0 && $userComboInfo['month_day'] <= 0) {
                        throw new Exception(Lang::get('project_no_combo'), 1);
                    }
                    break;
                case 2:
                    if ($userComboInfo['works_once_nums'] <= 0 && $userComboInfo['works_month_nums'] <= 0) {
                        throw new Exception(Lang::get('career_no_combo'), 1);
                    }
                    break;
                case 3:
                    if ($userComboInfo['emotion_once_nums'] <= 0 && $userComboInfo['emotion_month_nums'] <= 0) {
                        throw new Exception(Lang::get('emotion_no_combo'), 1);
                    }
                    break;
                case 4:
                    if ($userComboInfo['pr_once_nums'] <= 0 && $userComboInfo['pr_month_nums'] <= 0) {
                        throw new Exception(Lang::get('pr_no_combo'), 1);
                    }
                     break;
                case 5:
                    if ($userComboInfo['group_once_nums'] <= 0 && $userComboInfo['group_month_nums'] <= 0) {
                        throw new Exception(Lang::get('group_no_combo'), 1);
                    }
                    break;
            }
            $input_data = [];
            $me_name = ''; //我方名称
            $ta_name = ''; //他方名称
            $params = [$data['tpl']];
            $questions = explode(',', $data['questions']);
            
            foreach ($questions as $question) {
                $val = input($question, '');
                $params[] = $val;
                if ($data['me_name_key'] == $question) {
                    $me_name = $val;
                }
                if ($data['ta_name_key'] == $question) {
                    $ta_name = $val;
                }
                $input_data[] = [$question, $val];
            }
            $question_msg = call_user_func_array('sprintf', $params);

            //预测日期
            $result_day = date('Y-m-d');
            $date1 = input('date1', '');
            $isShowTimes = $date1 == '' ? 0 : 1;
            $contact = input('contact', 0);

            # 随机取一个. 如果是: 项目预测:1 + 公关审核:4 + 公司用户:5
            if ($type == 1 || $type == 4 || $type == 5)   $typeIds = Db::name('docs_latest')->field('id')->select();
            # 随机取一个. 如果是: 工作事业选择: 2
            if ($type == 2)   $typeIds = Db::name('docs_works')->field('id')->select();
            # 随机取一个. 如果是: 情感咨询选择: 3
            if ($type == 3)   $typeIds = Db::name('docs_emotion')->field('id')->select();

            $typeIdsArr = array_column($typeIds, 'id');
            # 从数组里面随机取出一个
            $key    = array_rand($typeIdsArr, 2);
            if (empty($key)) {
                throw new Exception(Lang::get('prediction_failed'), 1);
            }
            $result_id     = $typeIdsArr[$key[0]];
            $ta_result_id     = $typeIdsArr[$key[1]];

            $insertData = [
                'user_phone' => $user_phone,
                'person_menu_id' => $data['cid3'],
                'person_menu_item_id' => $data['id'],
                'person_fix_msg' => $question_msg,
                'result_id' => $result_id,
                'is_show_time_res' => $isShowTimes, //有预测日期
                'add_time' => date('Y-m-d H:i:s', time()),
                'result_type' => $data['answer_type'],
                'question_id' => $question_id,
                'ta_result_id' => $ta_result_id,
                'contact' => $contact,
                'date1' => $date1,
                'result_day' => $result_day,
                'rate' => 0,
                'me_name' => $me_name,
                'ta_name' => $ta_name,
                'input_data' => json_encode($input_data, JSON_UNESCAPED_UNICODE),
                'time_pay' => $time_pay
            ];
            $historyId = Db::name('new_user_question_history')->insertGetId($insertData);
            if ($historyId < 1) {
                throw new Exception(Lang::get('consultation_failed'), 1);
            }
            # 无月卡套餐, 扣减次数.有月卡继续执行
            switch ($type) {
                case 1:
                    if ($userComboInfo['month_day'] <= 0) {
                        # 用户表扣减次数
                        Db::name('member')->where(['phone' => $user_phone])->setDec('once_nums');
                    }
                    break;
                case 2:
                    if ($userComboInfo['works_month_nums'] <= 0) {
                        # 用户表扣减次数
                        Db::name('member')->where(['phone' => $user_phone])->setDec('works_once_nums');
                    }
                    break;
                case 3:
                    if ($userComboInfo['emotion_month_nums'] <= 0) {
                        # 用户表扣减次数
                        Db::name('member')->where(['phone' => $user_phone])->setDec('emotion_once_nums');
                    }
                    break;
                case 4:
                    if ($userComboInfo['pr_month_nums'] <= 0) {
                        # 用户表扣减次数
                        Db::name('member')->where(['phone' => $user_phone])->setDec('pr_once_nums');
                    }
                    break;
                case 5:
                    if ($userComboInfo['group_month_nums'] <= 0) {
                        # 用户表扣减次数
                        Db::name('member')->where(['phone' => $user_phone])->setDec('group_once_nums');
                    }
                    break;
            }

            $res['code'] = 0;
            $res['data']['history_id'] = $historyId;
            return json($res);
        } catch (\Throwable $th) {
            $res['code'] = 1;
            $res['msg'] = $th->getMessage();
            return json($res);
        }
    }
    //看广告免费咨询或查看
    public function adShow(){
        $res = ['code' => 1, 'data' => [], 'msg' => ''];
        $type = input('type', '1');//看广告类型 1 付费咨询 2 查看日期 3 解决方案
        $user_phone = input('user_phone', '');
        $historyId = input('history_id', '0');
        try {
            if (empty($user_phone)) {
                throw new Exception("手机号为必填参数", 1);
            }
            //看广告免费咨询
            if($type == 1){
                $answer_type = input('answer_type', '');
                 switch ($answer_type) {
                    case 1:
                        $result = Db::name('member')->where(['phone' => $user_phone])->update(['once_nums'=>1]);
                        break;
                    case 2:
                        $result = Db::name('member')->where(['phone' => $user_phone])->update(['works_once_nums'=>1]);
                        break;
                    case 3:
                        $result = Db::name('member')->where(['phone' => $user_phone])->update(['emotion_once_nums'=>1]);
                        break;
                    case 4:
                         $result = Db::name('member')->where(['phone' => $user_phone])->update(['pr_once_nums'=>1]);
                         break;
                    case 5:
                         $result = Db::name('member')->where(['phone' => $user_phone])->update(['group_once_nums'=>1]);
                        break;
                }
            }
            //日期免费查看
            if($type == 2){
                if (empty($historyId)) {
                    throw new Exception(Lang::get('consultation_id_required'), 1);
                }
                $result = Db::name('new_user_question_history')->where(['id' => $historyId])->update(['time_pay'=>1]);
            }
            //解决方案
            if($type == 3){
                if (empty($historyId)) {
                    throw new Exception(Lang::get('consultation_id_required'), 1);
                }
                $result = Db::name('new_user_question_history')->where(['id' => $historyId])->update(['resolve_pay'=>1]);
            }
       
            $res['code'] = 0;
            return json($res);
        } catch (\Throwable $th) {
            $res['code'] = 1;
            $res['msg'] = $th->getMessage();
            return json($res);
        }
    }
    /**
     * 获取预测信息
     *
     * @return void
     */
    public function  getPredict()
    {
        $res = ['code' => 1, 'data' => [], 'msg' => ''];
        try {
            # 个人 咨询,历史记录   145620
            $historyId = input('history_id', '0');
            // $historyId = 146175;
            $flag = input('flag',0);//是否记录缓存的标志
            if (empty($historyId)) {
                throw new Exception(Lang::get('consultation_id_required'), 1);
            }
            # 根据 $historyId, 得出它咨询所 得到的答案ID
            $historyInfo = Db::name('new_user_question_history')->field('*')->where(['id' => $historyId])->find();
            $phone = $historyInfo['user_phone'];
            // print_r($historyInfo);exit;
            if (empty($historyInfo)) {
                throw new Exception("未查询到咨询结果!", 1);
            }

            //v3 老数据兼容
            if (in_array($historyInfo['person_menu_id'], [1, 2, 3, 4,])) {
                $type = $historyInfo['person_menu_id'];
                $itypes = $historyInfo['person_menu_item_id'];
                $resultId = $historyInfo['result_id'];

                # 咨询配置
                $personConf = config('personal_consult_tmpl');
                # 根据 大小菜单, 确认用户提问信息
                $personTpl = isset($personConf[$type]['items'][$itypes]) ? $personConf[$type]['items'][$itypes] : '';
                if($personTpl != '') {
                    # 如果是 工作事业选择
                    if ($itypes == 4) $personTpl = sprintf($personTpl, $historyInfo['person_fix_msg'], $historyInfo['person_job']);
                    # 非工作事业选择
                    if ($itypes != 4) $personTpl = sprintf($personTpl, $historyInfo['person_fix_msg']);
                }


                $info = [];
                # 随机取一个. 如果是: 项目预测: 1 + 公关审核
                if ($type == 1 || $type == 4) $info = Db::name('docs_latest')->field('*')->where(['id' => $resultId])->find();
                # 随机取一个. 如果是: 工作事业选择: 2
                if ($type == 2)   $info = Db::name('docs_works')->field('*')->where(['id' => $resultId])->find();
                # 随机取一个. 如果是: 情感咨询选择: 3
                if ($type == 3)   $info = Db::name('docs_emotion')->field('*')->where(['id' => $resultId])->find();
                if (empty($info)) {
                    throw new Exception("未查询到咨询结果!", 1);
                }
                # 循环数据里面的 每个 value.替换 \n为 <br/>
                foreach ($info as $kItem => $kVal) {
                    $info[$kItem] = str_replace('\n', '<br/>', $info[$kItem]);
                }
                $info['resolve_pay'] = $historyInfo['resolve_pay'];
                $info['is_show_time_res'] = 1;
                $info['person_tpl'] = $personTpl;
                $res['code'] = 0;
                $res['data'] = $info;

                return json($res);
            }

            //v6 新数据逻辑
            $meResultId = $historyInfo['result_id'];
            $taResultId = $historyInfo['ta_result_id'];
            # 用户提问信息
            $personTpl = $historyInfo['person_fix_msg'];

            $type = $historyInfo['person_menu_id'];
            $table = 'docs_latest';////项目预测
            if($type == '2' || $type == '8') {
                $table = 'docs_works'; //工作事业
            }
            if ($type == '3' || $type == '9') {
                $table = 'docs_emotion'; //工作事业
            }
            $infoMe = Db::name($table)->field('*')->where(['id' => $meResultId])->find();
 
            $infoTa = Db::name($table)->field('*')->where(['id' => $taResultId])->find();
            if(empty($infoMe) || empty($infoTa)) {
                throw new Exception("未查询到咨询结果!", 1);
            }

            $num_sn = $infoMe['num_sn'];
            $me = $num_sn[7] > 3 ? $num_sn[1] : $num_sn[0];
            $ta = $num_sn[7] > 3 ? $num_sn[0] : $num_sn[1];
            // print_r($num_sn);exit;
            //使用me的编号进行预测
            if (!empty($historyInfo['me_name']) && empty($historyInfo['ta_name'])) {
                $tmp = $ta;
                $ta = $me;
                $me = $tmp;
            }
            $day = date('Y-m-d');
            if (!empty($historyInfo['result_day'])) {
                $day = $historyInfo['result_day'];
            }
          
            if ($historyInfo['is_show_time_res'] != 1 && $historyInfo['contact'] != 1) { //没有建立联系
                $day = date('Y-m-d', strtotime($day) + 30 * 86400); //下月日期预测
            }
            
              //年月日咨询日期
            $date1 = $historyInfo['date1'];
            $yearGood = [];
            $monthGood = [];
            $dayGood = [];
            $lenDate1 = strlen($date1);
                if ($lenDate1 == 10) {
                    $day = $date1;
                } else if ($lenDate1 == 7) {
                    $day = $date1 . '-01';
                } else if ($lenDate1 == 4) {
                    $day = $date1 . '-01-01';
                }
                // print_r($ta,$day);exit;
                $yuce = $this->_yuce($ta, $day);
                // print_r($yuce);exit;
              
                foreach ($yuce['years'] as $key => $value) {
                    if ($value[2]) {
                        $yearGood[] = $value[0];
                    }
                    if (count($yearGood) >= 4) {
                        break;
                    }
                }
                foreach ($yuce['months'] as $key => $value) {
                    if ($value[2]) {
                        $monthGood[] = $value[0];
                    }
                }
                foreach ($yuce['days'] as $key => $value) {
                    if ($value[2] ) {
                        $dayGood[] = $value[0];
                    }
                }
                // dump($yuce['days']);exit;
                
            $easy = 0;
            $easyNum = array_sum($yuce['ymd']);
            if ($historyInfo['is_show_time_res'] == 1) { //已知事件结果发生日期
                if ($lenDate1 == 10) {//年月日
                    $easy = $yuce['ymd'][2];
                } else if ($lenDate1 == 7) {//年月
                    $easy = $yuce['ymd'][1];
                } else if ($lenDate1 == 4) {//年
                    $easy = $yuce['ymd'][0];
                } else{
                    $easy = $easyNum > 1 ?1 : 0;
                }
                //新增逻辑2023 10-31
                // 11xxxx，12xxxx，21xxxx，22xxxx，33xxxx，44xxxx，45xxxx，54xxxx，55xxxx，66xxxx，77xxxx，78xxxx，87xxxx，88xxxx；
                // 61/62xxxx（1/2/3），16/12xxxx（4/5/6），18/28/17/27xxxx（1/2/3），81/82/71/72xxxx（4/5/6），34/35xxxx（1/2/3），
                //  43/53xxxx（4/5/6），46/56xxxx（1/2/3），64/65xxxx（4/5/6），83/73xxxx（4/5/6），38/37xxxx（1/2/3）
                if($historyInfo['contact'] == 0 && $easy == 1){
                   
                    $startNum = substr($num_sn,0,2);//开头两数字
                    $endMum = substr($num_sn,7,1);//括号里面的数字

                    if(in_array($startNum,[11,12,21,22,33,44,45,54,55,66,77,78,87,88]) ||(in_array($startNum,[61,62]) && in_array($endMum,[1,2,3])) ||
                    (in_array($startNum,[16,12]) && in_array($endMum,[4,5,6])) || (in_array($startNum,[18,28,17,27]) && in_array($endMum,[1,2,3])) ||
                    (in_array($startNum,[81,82,71,72]) && in_array($endMum,[4,5,6])) || (in_array($startNum,[34,35]) && in_array($endMum,[1,2,3])) ||
                    (in_array($startNum,[43,53]) && in_array($endMum,[4,5,6])) || (in_array($startNum,[46,56]) && in_array($endMum,[1,2,3])) ||
                    (in_array($startNum,[64,65]) && in_array($endMum,[4,5,6])) || (in_array($startNum,[83,73]) && in_array($endMum,[4.5,6])) ||
                    (in_array($startNum,[38,37]) && in_array($endMum,[1,2,3])))
                    {
                        $easy = 1;
                    }else{
                        $easy = 0;
                    }
                                       
                }
            } else { //无具体出结果日期事件
                $easy = $easyNum > 1 ? 1 : 0;
            }
            //startdate--enddate 时间区间预测
            $startdate = '';
            $enddate = '';

            $input_data_arr = json_decode($historyInfo['input_data'],true);
            if(is_array($input_data_arr)) {
                foreach ($input_data_arr as $value) {
                    if($value[0] == 'startdate') {
                        $startdate = $value[1];
                    }
                    if ($value[0] == 'enddate') {
                        $enddate = $value[1];
                    }
                }
            }
            $startenddate = [];
            if($startdate != '') {
                $tm = strtotime($startdate);
                $yuce2 = $this->_yuce($ta, $startdate);
                foreach ($yuce2['days'] as $key => $value) {
                    $nowDay = date("Y-m-d", $tm + $key * 86400);
                    if($nowDay > $enddate || count($startenddate)>=30) {
                        break;
                    }
                    if ($value[2]) {
                        $startenddate[] = $nowDay;
                    }
                }
            }
            
           
            //手机号中间4位用****替代
            $historyInfo['user_phone'] = substr_replace($historyInfo['user_phone'], '****', 3, 4);
            //我方 另一方名称处理
            if(!empty($historyInfo['me_name']) && empty($historyInfo['ta_name'])) {
                $historyInfo['ta_name'] = $historyInfo['user_phone'];
            } elseif(empty($historyInfo['me_name'])) {
                $historyInfo['me_name'] = $historyInfo['user_phone'];
            }

           
            if($table == 'docs_latest') {
                $resp = [
                    'num_sn' => $infoMe['num_sn'],
                    'question_msg' => $historyInfo['person_fix_msg'],
                    'is_get_profit' => $infoMe['is_get_profit'], //我方做该事件是否可以获得利益
                    'me_wants' => $infoMe['zixun_wants'], //我方推进意愿 zixun_wants
                    'ta_idea' => $infoTa['ke_zhu_idea'], //另一方对我的想法 ta ke_zhu_idea
                    'ta_xinli' => $infoMe['ke_zhu_idea'], //另一方对于该事件此时的心理活动 ta zixun_xinli
                    'ta_wants' => $infoTa['zixun_wants'], //对方增加事件内容一 ta zixun_wants
                    //年：月：日：
                    'year_good' => implode('、', $yearGood),
                    'month_good' => implode('、', $monthGood),
                    'day_good' => implode('、', $dayGood),
                    'easy' => $easy,
                    'date1' => $historyInfo['date1'], //咨询日期
                    'startenddate' => implode("\n", $startenddate),//时间区间预测
                    'me_wants_date' => '我方有推进意愿的时间（年月日）' . $historyInfo['result_day'],
                    //对方增加事件内容二  我方有推进意愿的时间（年月日）
                    'ta_xintai' => $infoTa['zixun_xintai'], //客方心态 ta zixun_xintai
                    'me_xintai' => $infoMe['zixun_xintai'], //我方的心态 zixun_xintai
                    'things_degree' => $infoMe['things_degree'], //该事件总体推进难易度 things_degree
                    'me_xinli' => $infoMe['zixun_xinli'], //我方对于该事件此时的心理活动 zixun_xinli
                    'rate' => $historyInfo['rate'], //指定风险管理推送频率
                    'solution' => $infoMe['solution'], //解决方案
                    'is_show_time_res' => $historyInfo['is_show_time_res'],
                    'me_name' => empty($historyInfo['me_name']) ? '我方' : $historyInfo['me_name'],
                    'ta_name' => empty($historyInfo['ta_name']) ? '另一方' : $historyInfo['ta_name'],
                    'contact' => $historyInfo['contact'], 
                    'question_id' => $historyInfo['question_id'],
                ];
                   if($historyInfo['date1']!=''){
                    $resp['me_wants_date'] = '我方有推进意愿的时间（年月日）' . $historyInfo['date1'];
                }
          
            }
            if ($table == 'docs_works') {
                $resp = [
                    'num_sn' => $infoMe['num_sn'],
                    'question_msg' => $historyInfo['person_fix_msg'],
                    'is_get_profit' => $infoMe['me_is_getprofit'], //我方做该事件是否可以获得利益
                    'me_wants' => $infoMe['me_work_idea'], //我方推进意愿 zixun_wants
                    'ta_idea' => '', //另一方对我的想法 ta ke_zhu_idea
                    'ta_xinli' => $infoMe['cm_idea_for_me'], //另一方对于该事件此时的心理活动 ta zixun_xinli
                    'ta_wants' => $infoTa['me_work_idea'], //对方增加事件内容一 ta zixun_wants
                    //年：月：日：
                    'year_good' => implode('、', $yearGood),
                    'month_good' => implode('、', $monthGood),
                    'day_good' => implode('、', $dayGood),
                    'easy' => $easy,
                    'date1' => $historyInfo['date1'],
                    'startenddate' => implode("\n", $startenddate),//时间区间预测
                    'me_wants_date' => '我方有推进意愿的时间（年月日）' . $historyInfo['result_day'], //对方增加事件内容二  我方有推进意愿的时间（年月日）
                    'ta_xintai' => $infoTa['me_xintai'], //客方心态 ta zixun_xintai
                    'me_xintai' => $infoMe['me_xintai'], //我方的心态 zixun_xintai
                    'things_degree' => $infoMe['me_work_things_degree'], //该事件总体推进难易度 things_degree
                    'me_xinli' => $infoMe['me_xinli'], //我方对于该事件此时的心理活动 zixun_xinli
                    'rate' => $historyInfo['rate'], //指定风险管理推送频率
                    'solution' => $infoMe['cm_hope_me'], //解决方案
                    'is_show_time_res' => $historyInfo['is_show_time_res'],
                    'me_name' => empty($historyInfo['me_name']) ? '我方' : $historyInfo['me_name'],
                    'ta_name' => empty($historyInfo['ta_name']) ? '另一方' : $historyInfo['ta_name'],
                    'contact' => $historyInfo['contact'], 
                    'question_id' => $historyInfo['question_id'],
                ];
                 if($historyInfo['date1']!=''){
                    $resp['me_wants_date'] = '我方有推进意愿的时间（年月日）' . $historyInfo['date1'];
                }
            }
            if ($table == 'docs_emotion') {
                $resp = [
                    'num_sn' => $infoMe['num_sn'],
                    'question_msg' => $historyInfo['person_fix_msg'],
                    'is_get_profit' => '', //我方做该事件是否可以获得利益
                    'me_wants' => $infoMe['me_tuijin'], //我方推进意愿 zixun_wants
                    'ta_idea' => '', //另一方对我的想法 ta ke_zhu_idea
                    'ta_xinli' => $infoMe['ta_wants'], //另一方对于该事件此时的心理活动 ta zixun_xinli  $infoTa['me_xinli']
                    'ta_wants' => $infoTa['me_tuijin'], //对方增加事件内容一 ta zixun_wants
                    //年：月：日：
                    'year_good' => implode('、', $yearGood),
                    'month_good' => implode('、', $monthGood),
                    'day_good' => implode('、', $dayGood),
                    'easy' => $easy,
                    'date1' => $historyInfo['date1'],
                    'startenddate' => implode("\n", $startenddate),//时间区间预测
                    'me_wants_date' => '我方有推进意愿的时间（年月日）'.$historyInfo['result_day'], //对方增加事件内容二  我方有推进意愿的时间（年月日）
                    'ta_xintai' => $infoTa['me_xintai'], //客方心态 ta zixun_xintai
                    'me_xintai' => $infoMe['me_xintai'], //我方的心态 zixun_xintai
                    'things_degree' => $infoMe['me_tuijin_degree'], //该事件总体推进难易度 things_degree
                    'me_xinli' => $infoMe['me_xinli'], //我方对于该事件此时的心理活动 zixun_xinli
                    'rate' => $historyInfo['rate'], //指定风险管理推送频率
                    'solution' => $infoMe['ta_hope_me'], //解决方案
                    'is_show_time_res' => $historyInfo['is_show_time_res'],
                    'me_name' => empty($historyInfo['me_name']) ? '我方' : $historyInfo['me_name'],
                    'ta_name' => empty($historyInfo['ta_name']) ? '另一方' : $historyInfo['ta_name'],
                    'contact' => $historyInfo['contact'], 
                    'question_id' => $historyInfo['question_id'],
                ];
                     if($historyInfo['date1']!=''){
                    $resp['me_wants_date'] = '我方有推进意愿的时间（年月日）' . $historyInfo['date1'];
                }
         
            }
            foreach ($resp as $kItem => $kVal) {
                // $resp['ta_name'] = substr_replace($resp['ta_name'], '****', 3, 4); 
                $resp[$kItem] = str_replace('\n', "\n", $resp[$kItem]);
            }

            $result_title = Db::name('result_title')->field('*')->find();
            // if($resp['ta_name']!=''){
            //       $ta_names = substr_replace($resp['ta_name'], '****', 3, 4); 
            // }else{
            //       $ta_names = ''; 
            // }

            foreach ($result_title as $kItem => $kVal) {
                $kVal = str_replace('{{me}}', $resp['me_name'], $kVal);
                $result_title[$kItem] = str_replace('{{ta}}',$resp['ta_name'], $kVal);
            }
            $resp['result_title'] = $result_title;

          
            //当时股市问题时回显用户conact 字段
            if( $historyInfo['contact'] == '1'){
                $resp['contact_text'] = '是';
            }elseif($historyInfo['contact'] == '2'){
                 $resp['contact_text'] = '股市';
            }else{
                 $resp['contact_text'] = '否';
            }
            $last_num = substr($infoMe['num_sn'],-1);
            $resp['last_num_text'] = '不建议';
            if($last_num == 1){
                 $resp['last_num_text'] = '可以用';
            }
            //如果是股市单独判断
           if(in_array($historyInfo['question_id'],[34,35,55,56]) && $historyInfo['contact'] == 2){
               if($last_num == 1 && $easy == 1) $resp['last_num_text'] = '可以用';
           }
            $resp['q_flag'] = 1;
            $resp['g_flag'] = 1;
            $resp['date_text'] = '容易';
            //查询用户的月卡信息 
            $userMonth = Db::name('member')->where(['phone'=>$phone])->field('month_day,works_month_nums,emotion_month_nums,pr_month_nums,group_month_nums')->find();
            //股票专用 ===如果是团体/个人 公关审核第三个问题将提问id 放入缓存队列自动提问
            if(in_array($historyInfo['question_id'],[34,35,55,56]) && $flag == 100){
                //查询是否有月卡.有月卡才自动提问
                $redisFlag = 0;
                if($historyInfo['result_type'] == 4){
                    if($userMonth['pr_month_nums'] > 0)  $redisFlag = 1;
                }
                if($historyInfo['result_type'] == 5){
                    if($userMonth['group_month_nums'] > 0)  $redisFlag = 1;
                }
                if($redisFlag){
                     $redis = new Redis();
                     $redis->handler()->lpush('autoList',$historyId);
                }
                
            }
            // contact 1 普通返回 0 特殊编号 2 股市
            if(in_array($historyInfo['question_id'],[34,35,55,56])){
                if($historyInfo['contact'] == 2){
                    if($last_num == 0)  $resp['g_flag'] = 0;//如果股票尾号是0 则整体年月日都不展示
                }
                 $resp['q_flag'] = 0;
                 $resp['date_text'] = '会';
                //选否：特殊编号组会+编号尾号1（建议）/0（不建议）。
                if($historyInfo['contact'] == 0 && $easy == 1){
                    $startNum = substr($num_sn,0,2);//开头两数字
                    $endMum = substr($num_sn,7,1);//括号里面的数字
                    if($last_num == 1){
                        if(in_array($startNum,[11,12,21,22,33,44,45,54,55,66,77,78,87,88]) ||(in_array($startNum,[61,62]) && in_array($endMum,[1,2,3])) ||
                        (in_array($startNum,[16,12]) && in_array($endMum,[4,5,6])) || (in_array($startNum,[18,28,17,27]) && in_array($endMum,[1,2,3])) ||
                        (in_array($startNum,[81,82,71,72]) && in_array($endMum,[4,5,6])) || (in_array($startNum,[34,35]) && in_array($endMum,[1,2,3])) ||
                        (in_array($startNum,[43,53]) && in_array($endMum,[4,5,6])) || (in_array($startNum,[46,56]) && in_array($endMum,[1,2,3])) ||
                        (in_array($startNum,[64,65]) && in_array($endMum,[4,5,6])) || (in_array($startNum,[83,73]) && in_array($endMum,[4.5,6])) ||
                        (in_array($startNum,[38,37]) && in_array($endMum,[1,2,3]))){
                            $resp['last_num_text'] = '建议';
                        }
                    }
                }
                // 常规编号会+编号尾号是1的。选是：常规编号会+编号尾号1（建议）/0（不建议）
                if($historyInfo['contact'] == 2 && $easy == 1){
                    if($last_num == 1){
                        $resp['last_num_text'] = '建议';
                    }
                }
                //单独处理股票建议的年月日 $startenddate
                $resp['startenddate'] = '';
                $respDay = [];
                $dayArr =  $this->_date($historyInfo['input_data']);
                if($dayArr){
                    foreach($dayArr as $datei){
                        if(in_array($datei,$startenddate)) $respDay[] = $datei;
                    }
                }
                if($respDay) $resp['startenddate'] = implode("\n", $respDay);
            }
            //是否付费
            $resp['resolve_pay'] = $historyInfo['resolve_pay'];;
            //如果未支付查询是否开通月卡===有开通月卡不收费
            if($resp['resolve_pay'] == 0){
                //判断是否有月卡
                 switch ($historyInfo['result_type']) {
                    case 1:
                        if ($userMonth['month_day'] > 0) {
                            $resp['resolve_pay'] = 1;
                        }
                        break;
                    case 2:
                        if ($userMonth['works_month_nums'] > 0) {
                           $resp['resolve_pay'] = 1;
                        }
                        break;
                    case 3:
                        if ($userMonth['emotion_month_nums'] > 0) {
                            $resp['resolve_pay'] = 1;
                        }
                        break;
                    case 4:
                        if ($userMonth['pr_month_nums'] > 0) {
                            $resp['resolve_pay'] = 1;
                        }
                        break;
                    case 5:
                        if ($userMonth['group_month_nums'] > 0) {
                           $resp['resolve_pay'] = 1;
                        }
                        break;
                }
            }
             //时间会否
            $resp['time_pay'] = $historyInfo['time_pay'];
            if($resp['time_pay'] == 0){
                //判断是否有月卡
                 switch ($historyInfo['result_type']) {
                    case 1:
                        if ($userMonth['month_day'] > 0) {
                            $resp['time_pay'] = 1;
                        }
                        break;
                    case 2:
                        if ($userMonth['works_month_nums'] > 0) {
                           $resp['time_pay'] = 1;
                        }
                        break;
                    case 3:
                        if ($userMonth['emotion_month_nums'] > 0) {
                            $resp['time_pay'] = 1;
                        }
                        break;
                    case 4:
                        if ($userMonth['pr_month_nums'] > 0) {
                            $resp['time_pay'] = 1;
                        }
                        break;
                    case 5:
                        if ($userMonth['group_month_nums'] > 0) {
                           $resp['time_pay'] = 1;
                        }
                        break;
                }
            }
            //页面有无利益颜色
            $resp['last_num_css'] = 'green_1';
            if($resp['last_num_text'] == '可以用'){
                $resp['last_num_css'] = 'green_2';
            }
            //查询频率开关
            $resp['rate_value'] =  Db::name('config')->where(['id'=>22])->value('value');
            //二维码
            $resp['qrcode'] = 'https://docs.wmta.cn/static/qrcode/'.$historyInfo['person_menu_id'].'-'.$historyInfo['person_menu_item_id'].'.jpg';
           
            $res['code'] = 0;
            $res['data'] = $resp;
            return json($res);
        } catch (\Throwable $th) {
            $res['code'] = 1;
            $res['msg'] = $th->getMessage();
            return json($res);
        }
    }
    //自动提问
    public function autoQuestion(){
        $redis = new Redis();
        $historyId = $redis->handler()->rpop('autoList');
        if($historyId){
              
            $historyInfo = Db::name('new_user_question_history')->field('*')->where(['id' => $historyId])->find();
            
            $inputData = $historyInfo['input_data'];
           
            
            $data = Db::name('question_new')->field('*')->where(['id' => $historyInfo['question_id']])->find();
            if (empty($data)) {
                trace('预测失败 question_id 不存在','info');
            }
            
            $type = $data['answer_type'];
            $input_data = [];
            $me_name = ''; //我方名称

            //预测日期
            $result_day = date('Y-m-d');

            # 随机取一个. 如果是: 项目预测:1 + 公关审核:4 + 公司用户:5
            if ($type == 1 || $type == 4 || $type == 5)   $typeIds = Db::name('docs_latest')->field('id')->select();
            # 随机取一个. 如果是: 工作事业选择: 2
            if ($type == 2)   $typeIds = Db::name('docs_works')->field('id')->select();
            # 随机取一个. 如果是: 情感咨询选择: 3
            if ($type == 3)   $typeIds = Db::name('docs_emotion')->field('id')->select();

            $typeIdsArr = array_column($typeIds, 'id');
            //股市
            if(in_array($historyInfo['question_id'],[34,35])){
                 $dayArr =  $this->_date($inputData);
                //入库
                if(count($dayArr) >0){
                     $inputData = json_decode($inputData,true);
                     $ta_name = $inputData[3][1];
                    foreach ($dayArr as $d){
                        # 从数组里面随机取出一个
                        $key    = array_rand($typeIdsArr, 2);
                        if (empty($key)) {
                             trace('预测失败','info');
                        }
                        $historyInfo['person_fix_msg']  = $d.$inputData[2][1].',会'.$inputData[3][1].'吗?';
                      
                       
                        $result_id     = $typeIdsArr[$key[0]];
                        $ta_result_id     = $typeIdsArr[$key[1]];
                       
                    //   [["title1","我"],["date1","2024-01-16"],["title2","有好运"]]
                    //  json_encode($input_data, JSON_UNESCAPED_UNICODE),
                        $input_data[] = [$inputData[2][0],$inputData[2][1]];
                        $input_data[] = ['date1',$d];
                        $input_data[] = [$inputData[3][0],$inputData[3][1]];
                        $historyInfo['input_data'] = json_encode($input_data, JSON_UNESCAPED_UNICODE);
                        $historyInfo['date1'] = $inputData[0][1];
                        $historyInfo['is_show_time_res'] = 1;
                      
                        unset($historyInfo['id']);
                        $historyInfo['ta_name'] = $ta_name;
                        $historyInfo['result_day'] = $result_day;
                        
                        $historyInfo['ta_result_id'] = $ta_result_id;
                        $historyInfo['add_time'] = date('Y-m-d H:i:s', time());
                        $historyInfo['date1'] = $d;
                        $historyInfo['result_id'] = $result_id;
                        $historyInfo['resolve_pay'] = 0;
                        $historyInfo['time_pay'] = 0;
                        $historyId = Db::name('new_user_question_history')->insertGetId($historyInfo);
                        $input_data = [];
                        if(!$historyId)  trace('预测失败 入库失败','info');
                    }
                }
            }
            
            //股市带区间
            if(in_array($historyInfo['question_id'],[55,56])){
                //入库
                    $inputData = json_decode($inputData,true);
                     $numArr = $this->_num($inputData[3][1],$inputData[4][1]);
                     $ta_name = $inputData[2][1];
                    foreach ($numArr as $d){
                        # 从数组里面随机取出一个
                        $key    = array_rand($typeIdsArr, 2);
                        if (empty($key)) {
                             trace('预测失败','info');
                        }
                        $historyInfo['person_fix_msg']  = $inputData[0][1].'（年月日）--'.$inputData[1][1].'（年月日）'.$inputData[2][1].',会到'.$d.'吗';
                   
                       
                        $result_id     = $typeIdsArr[$key[0]];
                        $ta_result_id     = $typeIdsArr[$key[1]];
                        
                       
                      
                        unset($historyInfo['id']);
                        $historyInfo['ta_name'] = $ta_name;
                        $historyInfo['result_day'] = $result_day;
                        
                        $historyInfo['ta_result_id'] = $ta_result_id;
                        $historyInfo['add_time'] = date('Y-m-d H:i:s', time());
                        $historyInfo['result_id'] = $result_id;
                        $historyInfo['resolve_pay'] = 0;
                        $historyInfo['time_pay'] = 0;
                       
                    //   dump($historyInfo);exit;
                        $historyId = Db::name('new_user_question_history')->insertGetId($historyInfo);
                        if(!$historyId)  trace('预测失败 入库失败','info');
                    }
                }
            }
        
    }
    //返回数字区间
    private function _num($min,$max){
        $numArr = [];
        if($min <500){
            for ($i = $min; $i <= $max; $i++) {
                $numArr[] = $i;
            }
        }
        if($min >=500 && $min <1000){
            for ($i = $min; $i <= $max; $i+=10) {
                $numArr[] = $i;
            }
        }
         if($min >=1000){
            for ($i = $min; $i <= $max; $i+=50) {
                $numArr[] = $i;
            }
        }
        return $numArr;
    }
    //根据时间返回中间中间所有的时间
    private function _date($inputData){
            $inputData = json_decode($inputData,true);
            $startDate = $inputData[0][1];
            $endDate = $inputData[1][1];
            $startTime = explode('-',$startDate);
            $endTime = explode('-',$endDate);
            $dayArr = [];
            //取得递增年
            if(count($startTime) == 1){
            	$startDateUnix = strtotime($startDate.'-01-01');
            	$endDateUnix = strtotime($endDate.'-01-01');
            	for($startDateUnix; $startDateUnix <= $endDateUnix;  $startDateUnix = strtotime('+1 year', $startDateUnix)){
            		$dayArr[] = date('Y',$startDateUnix); 
            	}
            	//删除第一个元素，因为已经提问了
            // 	array_shift($dayArr);
            }
            $startDateUnix = strtotime($startDate);
            $endDateUnix = strtotime($endDate);
            //取得递增月
            if(count($startTime) == 2){
            	for($startDateUnix; $startDateUnix <= $endDateUnix;  $startDateUnix = strtotime('+1 month', $startDateUnix)){
            		$dayArr[] = date('Y-m',$startDateUnix); 
            	}
            // 	array_shift($dayArr);
            }
            //取得递增日
            if(count($startTime) == 3){
            	for($startDateUnix; $startDateUnix <= $endDateUnix;  $startDateUnix = strtotime('+1 day', $startDateUnix)){
            		$dayArr[] = date('Y-m-d',$startDateUnix); 
            	}
            // 	array_shift($dayArr);
            }
            return $dayArr;
    }
    /**
     * 获取预测信息
     *
     * @return void
     */
    public function  getPredictsall()
    {
        $res = ['code' => 1, 'data' => [], 'msg' => ''];
        try {
            # 个人 咨询,历史记录
            $historyId = input('history_id', '0');
            // print_r($historyId);exit;
            if (empty($historyId)) {
                throw new Exception(Lang::get('consultation_id_required'), 1);
            }
            # 根据 $historyId, 得出它咨询所 得到的答案ID
            $historyInfo = Db::name('new_user_question_history')->field('*')->where(['id' => $historyId])->find();
            // print_r($historyInfo);exit;
            if (empty($historyInfo)) {
                throw new Exception("未查询到咨询结果!", 1);
            }
            // echo(1);exit;
            //v3 老数据兼容
            if (in_array($historyInfo['person_menu_id'], [1, 2, 3, 4,])) {
                $type = $historyInfo['person_menu_id'];
                $itypes = $historyInfo['person_menu_item_id'];
                $resultId = $historyInfo['result_id'];

                # 咨询配置
                $personConf = config('personal_consult_tmpl');
                # 根据 大小菜单, 确认用户提问信息
                $personTpl = isset($personConf[$type]['items'][$itypes]) ? $personConf[$type]['items'][$itypes] : '';
                if($personTpl != '') {
                    # 如果是 工作事业选择
                    if ($itypes == 4) $personTpl = sprintf($personTpl, $historyInfo['person_fix_msg'], $historyInfo['person_job']);
                    # 非工作事业选择
                    if ($itypes != 4) $personTpl = sprintf($personTpl, $historyInfo['person_fix_msg']);
                }


                $info = [];
                # 随机取一个. 如果是: 项目预测: 1 + 公关审核
                if ($type == 1 || $type == 4) $info = Db::name('docs_latest')->field('*')->where(['id' => $resultId])->find();
                # 随机取一个. 如果是: 工作事业选择: 2
                if ($type == 2)   $info = Db::name('docs_works')->field('*')->where(['id' => $resultId])->find();
                # 随机取一个. 如果是: 情感咨询选择: 3
                if ($type == 3)   $info = Db::name('docs_emotion')->field('*')->where(['id' => $resultId])->find();
                if (empty($info)) {
                    throw new Exception("未查询到咨询结果!", 1);
                }
                # 循环数据里面的 每个 value.替换 \n为 <br/>
                foreach ($info as $kItem => $kVal) {
                    $info[$kItem] = str_replace('\n', '<br/>', $info[$kItem]);
                }

                $info['is_show_time_res'] = 1;
                $info['person_tpl'] = $personTpl;
                $res['code'] = 0;
                $res['data'] = $info;

                return json($res);
            }

            //v6 新数据逻辑
            $meResultId = $historyInfo['result_id'];
            $taResultId = $historyInfo['ta_result_id'];
            # 用户提问信息
            $personTpl = $historyInfo['person_fix_msg'];

            $type = $historyInfo['person_menu_id'];
            $table = 'docs_latest';////项目预测
            if($type == '2' || $type == '8') {
                $table = 'docs_works'; //工作事业
            }
            if ($type == '3' || $type == '9') {
                $table = 'docs_emotion'; //工作事业
            }
            $infoMe = Db::name($table)->field('*')->where(['id' => $meResultId])->find();
 
            $infoTa = Db::name($table)->field('*')->where(['id' => $taResultId])->find();
            if(empty($infoMe) || empty($infoTa)) {
                throw new Exception("未查询到咨询结果!", 1);
            }

            $num_sn = $infoMe['num_sn'];
            $me = $num_sn[7] > 3 ? $num_sn[1] : $num_sn[0];
            $ta = $num_sn[7] > 3 ? $num_sn[0] : $num_sn[1];
            // print_r($num_sn);exit;
            //使用me的编号进行预测
            if (!empty($historyInfo['me_name']) && empty($historyInfo['ta_name'])) {
                $tmp = $ta;
                $ta = $me;
                $me = $tmp;
            }
            $day = date('Y-m-d');
            if (!empty($historyInfo['result_day'])) {
                $day = $historyInfo['result_day'];
            }
          
            if ($historyInfo['is_show_time_res'] != 1 && $historyInfo['contact'] != 1) { //没有建立联系
                $day = date('Y-m-d', strtotime($day) + 30 * 86400); //下月日期预测
            }
            
          
            //判断编码是否与日期和极端数字匹配
            $cd = substr($num_sn,0,2); 
            $anq = [11,12,21,22,33,44,45,54,55,66,77,78,87,88];
            //存在进下一步匹配
            if($historyInfo['date1']!=''){
                $times = $historyInfo['date1'];
                $timeslist = explode('-',$times);
                if(in_array($cd,$timeslist)){
                    if($historyInfo['contact']==0){
                        if(in_array($cd,$anq)){
                             $day = date('Y-m-d', strtotime($day)); //下月日期预测
                          }
                        //   else{
                        //     //$day = date('Y-m-d', strtotime($day) + 30 * 86400); //下月日期预测
                        //     throw new Exception("暂无结果!", 1);
                        //  }  
                    }
                    // else{
                    //      $day = date('Y-m-d', strtotime($day) + 30 * 86400); //下月日期预测
                    // }
                }
            }
              //年月日咨询日期
            $date1 = $historyInfo['date1'];
            $lenDate1 = strlen($date1);
            if ($lenDate1 == 10) {
                $day = $date1;
            } else if ($lenDate1 == 7) {
                $day = $date1 . '-01';
            } else if ($lenDate1 == 4) {
                $day = $date1 . '-01-01';
            }
            // print_r($ta,$day);exit;
            $yuce = $this->_yuce($ta, $day);
            // print_r($yuce);exit;
            $yearGood = [];
            $monthGood = [];
            $dayGood = [];
            foreach ($yuce['years'] as $key => $value) {
                if ($value[2]) {
                    $yearGood[] = $value[0];
                }
                if (count($yearGood) >= 4) {
                    break;
                }
            }
            foreach ($yuce['months'] as $key => $value) {
                if ($value[2]) {
                    $monthGood[] = $value[0];
                }
            }
            foreach ($yuce['days'] as $key => $value) {
                if ($value[2]) {
                    $dayGood[] = $value[0];
                }
            }
            $easyNum = array_sum($yuce['ymd']);
            if ($historyInfo['is_show_time_res'] == 1) { //已知事件结果发生日期
                if ($lenDate1 == 10) {//年月日
                    $easy = $yuce['ymd'][2];
                } else if ($lenDate1 == 7) {//年月
                    $easy = $yuce['ymd'][1];
                } else if ($lenDate1 == 4) {//年
                    $easy = $yuce['ymd'][0];
                } else {
                    $easy = $easyNum > 1 ? 1 : 0;
                }
            } else { //无具体出结果日期事件
                $easy = $easyNum > 1 ? 1 : 0;
            }

            //startdate--enddate 时间区间预测
            $startdate = '';
            $enddate = '';
            $input_data_arr = json_decode($historyInfo['input_data'],true);
            if(is_array($input_data_arr)) {
                foreach ($input_data_arr as $value) {
                    if($value[0] == 'startdate') {
                        $startdate = $value[1];
                    }
                    if ($value[0] == 'enddate') {
                        $enddate = $value[1];
                    }
                }
            }
            $startenddate = [];
            if($startdate != '') {
                $tm = strtotime($startdate);
                $yuce2 = $this->_yuce($ta, $startdate);
                foreach ($yuce2['days'] as $key => $value) {
                    $nowDay = date("Y-m-d", $tm + $key * 86400);
                    if($nowDay > $enddate || count($startenddate)>=30) {
                        break;
                    }
                    if ($value[2]) {
                        $startenddate[] = $nowDay;
                    }
                }
            }

            //手机号中间4位用****替代
            $historyInfo['user_phone'] = substr_replace($historyInfo['user_phone'], '****', 3, 4);
            //我方 另一方名称处理
            if(!empty($historyInfo['me_name']) && empty($historyInfo['ta_name'])) {
                $historyInfo['ta_name'] = $historyInfo['user_phone'];
            } elseif(empty($historyInfo['me_name'])) {
                $historyInfo['me_name'] = $historyInfo['user_phone'];
            }

            $resp = [];
            if($table == 'docs_latest') {
                $resp = [
                    'num_sn' => $infoMe['num_sn'],
                    'question_msg' => $historyInfo['person_fix_msg'],
                    'is_get_profit' => $infoMe['is_get_profit'], //我方做该事件是否可以获得利益
                    'me_wants' => $infoMe['zixun_wants'], //我方推进意愿 zixun_wants
                    'ta_idea' => $infoTa['ke_zhu_idea'], //另一方对我的想法 ta ke_zhu_idea
                    'ta_xinli' => $infoTa['zixun_xinli'], //另一方对于该事件此时的心理活动 ta zixun_xinli
                    'ta_wants' => $infoTa['zixun_wants'], //对方增加事件内容一 ta zixun_wants
                    //年：月：日：
                    'year_good' => implode('、', $yearGood),
                    'month_good' => implode('、', $monthGood),
                    'day_good' => implode('、', $dayGood),
                    'easy' => $easy,
                    'date1' => $historyInfo['date1'], //咨询日期
                    'startenddate' => implode("\n", $startenddate),//时间区间预测
                    'me_wants_date' => '我方有推进意愿的时间（年月日）' . $historyInfo['result_day'],
                    //对方增加事件内容二  我方有推进意愿的时间（年月日）
                    'ta_xintai' => $infoTa['zixun_xintai'], //客方心态 ta zixun_xintai
                    'me_xintai' => $infoMe['zixun_xintai'], //我方的心态 zixun_xintai
                    'things_degree' => $infoMe['things_degree'], //该事件总体推进难易度 things_degree
                    'me_xinli' => $infoMe['zixun_xinli'], //我方对于该事件此时的心理活动 zixun_xinli
                    'rate' => $historyInfo['rate'], //指定风险管理推送频率
                    'solution' => $infoMe['solution'], //解决方案
                    'is_show_time_res' => $historyInfo['is_show_time_res'],
                    'me_name' => empty($historyInfo['me_name']) ? '我方' : $historyInfo['me_name'],
                    'ta_name' => empty($historyInfo['ta_name']) ? '另一方' : $historyInfo['ta_name'],
                ];
                   if($historyInfo['date1']!=''){
                    $resp['me_wants_date'] = '我方有推进意愿的时间（年月日）' . $historyInfo['date1'];
                }
          
            }
            if ($table == 'docs_works') {
                $resp = [
                    'num_sn' => $infoMe['num_sn'],
                    'question_msg' => $historyInfo['person_fix_msg'],
                    'is_get_profit' => $infoMe['me_is_getprofit'], //我方做该事件是否可以获得利益
                    'me_wants' => $infoMe['me_work_idea'], //我方推进意愿 zixun_wants
                    'ta_idea' => '', //另一方对我的想法 ta ke_zhu_idea
                    'ta_xinli' => $infoTa['me_xinli'], //另一方对于该事件此时的心理活动 ta zixun_xinli
                    'ta_wants' => $infoTa['me_work_idea'], //对方增加事件内容一 ta zixun_wants
                    //年：月：日：
                    'year_good' => implode('、', $yearGood),
                    'month_good' => implode('、', $monthGood),
                    'day_good' => implode('、', $dayGood),
                    'easy' => $easy,
                    'date1' => $historyInfo['date1'],
                    'startenddate' => implode("\n", $startenddate),//时间区间预测
                    'me_wants_date' => '我方有推进意愿的时间（年月日）' . $historyInfo['result_day'], //对方增加事件内容二  我方有推进意愿的时间（年月日）
                    'ta_xintai' => $infoTa['me_xintai'], //客方心态 ta zixun_xintai
                    'me_xintai' => $infoMe['me_xintai'], //我方的心态 zixun_xintai
                    'things_degree' => $infoMe['me_work_things_degree'], //该事件总体推进难易度 things_degree
                    'me_xinli' => $infoMe['me_xinli'], //我方对于该事件此时的心理活动 zixun_xinli
                    'rate' => $historyInfo['rate'], //指定风险管理推送频率
                    'solution' => $infoMe['cm_hope_me'], //解决方案
                    'is_show_time_res' => $historyInfo['is_show_time_res'],
                    'me_name' => empty($historyInfo['me_name']) ? '我方' : $historyInfo['me_name'],
                    'ta_name' => empty($historyInfo['ta_name']) ? '另一方' : $historyInfo['ta_name'],
                ];
                 if($historyInfo['date1']!=''){
                    $resp['me_wants_date'] = '我方有推进意愿的时间（年月日）' . $historyInfo['date1'];
                }
            }
            if ($table == 'docs_emotion') {
                $resp = [
                    'num_sn' => $infoMe['num_sn'],
                    'question_msg' => $historyInfo['person_fix_msg'],
                    'is_get_profit' => '', //我方做该事件是否可以获得利益
                    'me_wants' => $infoMe['me_tuijin'], //我方推进意愿 zixun_wants
                    'ta_idea' => '', //另一方对我的想法 ta ke_zhu_idea
                    'ta_xinli' => $infoTa['me_xinli'], //另一方对于该事件此时的心理活动 ta zixun_xinli
                    'ta_wants' => $infoTa['me_tuijin'], //对方增加事件内容一 ta zixun_wants
                    //年：月：日：
                    'year_good' => implode('、', $yearGood),
                    'month_good' => implode('、', $monthGood),
                    'day_good' => implode('、', $dayGood),
                    'easy' => $easy,
                    'date1' => $historyInfo['date1'],
                    'startenddate' => implode("\n", $startenddate),//时间区间预测
                    'me_wants_date' => '我方有推进意愿的时间（年月日）'.$historyInfo['result_day'], //对方增加事件内容二  我方有推进意愿的时间（年月日）
                    'ta_xintai' => $infoTa['me_xintai'], //客方心态 ta zixun_xintai
                    'me_xintai' => $infoMe['me_xintai'], //我方的心态 zixun_xintai
                    'things_degree' => $infoMe['me_tuijin_degree'], //该事件总体推进难易度 things_degree
                    'me_xinli' => $infoMe['me_xinli'], //我方对于该事件此时的心理活动 zixun_xinli
                    'rate' => $historyInfo['rate'], //指定风险管理推送频率
                    'solution' => $infoMe['ta_hope_me'], //解决方案
                    'is_show_time_res' => $historyInfo['is_show_time_res'],
                    'me_name' => empty($historyInfo['me_name']) ? '我方' : $historyInfo['me_name'],
                    'ta_name' => empty($historyInfo['ta_name']) ? '另一方' : $historyInfo['ta_name'],
                ];
                     if($historyInfo['date1']!=''){
                    $resp['me_wants_date'] = '我方有推进意愿的时间（年月日）' . $historyInfo['date1'];
                }
         
            }
           
            foreach ($resp as $kItem => $kVal) {
                // $resp['ta_name'] = substr_replace($resp['ta_name'], '****', 3, 4); 
                $resp[$kItem] = str_replace('\n', "\n", $resp[$kItem]);
            }

            $result_title = Db::name('result_title')->field('*')->find();
            // if($resp['ta_name']!=''){
            //       $ta_names = substr_replace($resp['ta_name'], '****', 3, 4); 
            // }else{
            //       $ta_names = ''; 
            // }

            foreach ($result_title as $kItem => $kVal) {
                $kVal = str_replace('{{me}}', $resp['me_name'], $kVal);
                $result_title[$kItem] = str_replace('{{ta}}',$resp['ta_name'], $kVal);
            }
            $resp['result_title'] = $result_title;

            $res['code'] = 0;
            $res['data'] = $resp;
            return json($res);
        } catch (\Throwable $th) {
            $res['code'] = 1;
            $res['msg'] = $th->getMessage();
            return json($res);
        }
    }
    
    
    
      public function  getPredictall($historyId)
    {
        $res = ['code' => 1, 'data' => [], 'msg' => ''];
        try {
            # 个人 咨询,历史记录
            // $historyId = input('history_id', '0');
            if (empty($historyId)) {
                throw new Exception(Lang::get('consultation_id_required'), 1);
            }
            # 根据 $historyId, 得出它咨询所 得到的答案ID
            $historyInfo = Db::name('new_user_question_history')->field('*')->where(['id' => $historyId])->find();
            // print_r($historyInfo);exit;
            if (empty($historyInfo)) {
                throw new Exception("未查询到咨询结果!", 1);
            }

            //v3 老数据兼容
            if (in_array($historyInfo['person_menu_id'], [1, 2, 3, 4,])) {
                $type = $historyInfo['person_menu_id'];
                $itypes = $historyInfo['person_menu_item_id'];
                $resultId = $historyInfo['result_id'];

                # 咨询配置
                $personConf = config('personal_consult_tmpl');
                # 根据 大小菜单, 确认用户提问信息
                $personTpl = isset($personConf[$type]['items'][$itypes]) ? $personConf[$type]['items'][$itypes] : '';
                if($personTpl != '') {
                    # 如果是 工作事业选择
                    if ($itypes == 4) $personTpl = sprintf($personTpl, $historyInfo['person_fix_msg'], $historyInfo['person_job']);
                    # 非工作事业选择
                    if ($itypes != 4) $personTpl = sprintf($personTpl, $historyInfo['person_fix_msg']);
                }


                $info = [];
                # 随机取一个. 如果是: 项目预测: 1 + 公关审核
                if ($type == 1 || $type == 4) $info = Db::name('docs_latest')->field('*')->where(['id' => $resultId])->find();
                # 随机取一个. 如果是: 工作事业选择: 2
                if ($type == 2)   $info = Db::name('docs_works')->field('*')->where(['id' => $resultId])->find();
                # 随机取一个. 如果是: 情感咨询选择: 3
                if ($type == 3)   $info = Db::name('docs_emotion')->field('*')->where(['id' => $resultId])->find();
                if (empty($info)) {
                    throw new Exception("未查询到咨询结果!", 1);
                }
                # 循环数据里面的 每个 value.替换 \n为 <br/>
                foreach ($info as $kItem => $kVal) {
                    $info[$kItem] = str_replace('\n', '<br/>', $info[$kItem]);
                }

                $info['is_show_time_res'] = 1;
                $info['person_tpl'] = $personTpl;
                $res['code'] = 0;
                $res['data'] = $info;

                return json($res);
            }

            //v6 新数据逻辑
            $meResultId = $historyInfo['result_id'];
            $taResultId = $historyInfo['ta_result_id'];
            # 用户提问信息
            $personTpl = $historyInfo['person_fix_msg'];

            $type = $historyInfo['person_menu_id'];
            $table = 'docs_latest';////项目预测
            if($type == '2' || $type == '8') {
                $table = 'docs_works'; //工作事业
            }
            if ($type == '3' || $type == '9') {
                $table = 'docs_emotion'; //工作事业
            }
            $infoMe = Db::name($table)->field('*')->where(['id' => $meResultId])->find();
 
            $infoTa = Db::name($table)->field('*')->where(['id' => $taResultId])->find();
            if(empty($infoMe) || empty($infoTa)) {
                throw new Exception("未查询到咨询结果!", 1);
            }

            $num_sn = $infoMe['num_sn'];
            $me = $num_sn[7] > 3 ? $num_sn[1] : $num_sn[0];
            $ta = $num_sn[7] > 3 ? $num_sn[0] : $num_sn[1];
            // print_r($num_sn);exit;
            //使用me的编号进行预测
            if (!empty($historyInfo['me_name']) && empty($historyInfo['ta_name'])) {
                $tmp = $ta;
                $ta = $me;
                $me = $tmp;
            }
            $day = date('Y-m-d');
            if (!empty($historyInfo['result_day'])) {
                $day = $historyInfo['result_day'];
            }
          
            if ($historyInfo['is_show_time_res'] != 1 && $historyInfo['contact'] != 1) { //没有建立联系
                $day = date('Y-m-d', strtotime($day) + 30 * 86400); //下月日期预测
            }
            
          
            //判断编码是否与日期和极端数字匹配
            $cd = substr($num_sn,0,2); 
            $anq = [11,12,21,22,33,44,45,54,55,66,77,78,87,88];
            //存在进下一步匹配
            if($historyInfo['date1']!=''){
                $times = $historyInfo['date1'];
                $timeslist = explode('-',$times);
                if(in_array($cd,$timeslist)){
                    if($historyInfo['contact']==0){
                        if(in_array($cd,$anq)){
                             $day = date('Y-m-d', strtotime($day)); //下月日期预测
                          }
                        //   else{
                        //     //$day = date('Y-m-d', strtotime($day) + 30 * 86400); //下月日期预测
                        //     throw new Exception("暂无结果!", 1);
                        //  }  
                    }
                    // else{
                    //      $day = date('Y-m-d', strtotime($day) + 30 * 86400); //下月日期预测
                    // }
                }
            }
              //年月日咨询日期
            $date1 = $historyInfo['date1'];
            $lenDate1 = strlen($date1);
            if ($lenDate1 == 10) {
                $day = $date1;
            } else if ($lenDate1 == 7) {
                $day = $date1 . '-01';
            } else if ($lenDate1 == 4) {
                $day = $date1 . '-01-01';
            }
            // print_r($ta,$day);exit;
            $yuce = $this->_yuce($ta, $day);
            // print_r($yuce);exit;
            $yearGood = [];
            $monthGood = [];
            $dayGood = [];
            foreach ($yuce['years'] as $key => $value) {
                if ($value[2]) {
                    $yearGood[] = $value[0];
                }
                if (count($yearGood) >= 4) {
                    break;
                }
            }
            foreach ($yuce['months'] as $key => $value) {
                if ($value[2]) {
                    $monthGood[] = $value[0];
                }
            }
            foreach ($yuce['days'] as $key => $value) {
                if ($value[2]) {
                    $dayGood[] = $value[0];
                }
            }
            $easyNum = array_sum($yuce['ymd']);
            if ($historyInfo['is_show_time_res'] == 1) { //已知事件结果发生日期
                if ($lenDate1 == 10) {//年月日
                    $easy = $yuce['ymd'][2];
                } else if ($lenDate1 == 7) {//年月
                    $easy = $yuce['ymd'][1];
                } else if ($lenDate1 == 4) {//年
                    $easy = $yuce['ymd'][0];
                } else {
                    $easy = $easyNum > 1 ? 1 : 0;
                }
            } else { //无具体出结果日期事件
                $easy = $easyNum > 1 ? 1 : 0;
            }

            //startdate--enddate 时间区间预测
            $startdate = '';
            $enddate = '';
            $input_data_arr = json_decode($historyInfo['input_data'],true);
            if(is_array($input_data_arr)) {
                foreach ($input_data_arr as $value) {
                    if($value[0] == 'startdate') {
                        $startdate = $value[1];
                    }
                    if ($value[0] == 'enddate') {
                        $enddate = $value[1];
                    }
                }
            }
            $startenddate = [];
            if($startdate != '') {
                $tm = strtotime($startdate);
                $yuce2 = $this->_yuce($ta, $startdate);
                foreach ($yuce2['days'] as $key => $value) {
                    $nowDay = date("Y-m-d", $tm + $key * 86400);
                    if($nowDay > $enddate || count($startenddate)>=30) {
                        break;
                    }
                    if ($value[2]) {
                        $startenddate[] = $nowDay;
                    }
                }
            }

            //手机号中间4位用****替代
            $historyInfo['user_phone'] = substr_replace($historyInfo['user_phone'], '****', 3, 4);
            //我方 另一方名称处理
            if(!empty($historyInfo['me_name']) && empty($historyInfo['ta_name'])) {
                $historyInfo['ta_name'] = $historyInfo['user_phone'];
            } elseif(empty($historyInfo['me_name'])) {
                $historyInfo['me_name'] = $historyInfo['user_phone'];
            }
            $resp = [];
            if($table == 'docs_latest') {
                $resp = [
                    'num_sn' => $infoMe['num_sn'],
                    'question_msg' => $historyInfo['person_fix_msg'],
                    'is_get_profit' => $infoMe['is_get_profit'], //我方做该事件是否可以获得利益
                    'me_wants' => $infoMe['zixun_wants'], //我方推进意愿 zixun_wants
                    'ta_idea' => $infoTa['ke_zhu_idea'], //另一方对我的想法 ta ke_zhu_idea
                    'ta_xinli' => $infoTa['zixun_xinli'], //另一方对于该事件此时的心理活动 ta zixun_xinli
                    'ta_wants' => $infoTa['zixun_wants'], //对方增加事件内容一 ta zixun_wants
                    //年：月：日：
                    'year_good' => implode('、', $yearGood),
                    'month_good' => implode('、', $monthGood),
                    'day_good' => implode('、', $dayGood),
                    'easy' => $easy,
                    'date1' => $historyInfo['date1'], //咨询日期
                    'startenddate' => implode("\n", $startenddate),//时间区间预测
                    'me_wants_date' => '我方有推进意愿的时间（年月日）' . $historyInfo['result_day'],
                    //对方增加事件内容二  我方有推进意愿的时间（年月日）
                    'ta_xintai' => $infoTa['zixun_xintai'], //客方心态 ta zixun_xintai
                    'me_xintai' => $infoMe['zixun_xintai'], //我方的心态 zixun_xintai
                    'things_degree' => $infoMe['things_degree'], //该事件总体推进难易度 things_degree
                    'me_xinli' => $infoMe['zixun_xinli'], //我方对于该事件此时的心理活动 zixun_xinli
                    'rate' => $historyInfo['rate'], //指定风险管理推送频率
                    'solution' => $infoMe['solution'], //解决方案
                    'is_show_time_res' => $historyInfo['is_show_time_res'],
                    'me_name' => empty($historyInfo['me_name']) ? '我方' : $historyInfo['me_name'],
                    'ta_name' => empty($historyInfo['ta_name']) ? '另一方' : $historyInfo['ta_name'],
                ];
                   if($historyInfo['date1']!=''){
                    $resp['me_wants_date'] = '我方有推进意愿的时间（年月日）' . $historyInfo['date1'];
                }
            }
            if ($table == 'docs_works') {
                $resp = [
                    'num_sn' => $infoMe['num_sn'],
                    'question_msg' => $historyInfo['person_fix_msg'],
                    'is_get_profit' => $infoMe['me_is_getprofit'], //我方做该事件是否可以获得利益
                    'me_wants' => $infoMe['me_work_idea'], //我方推进意愿 zixun_wants
                    'ta_idea' => '', //另一方对我的想法 ta ke_zhu_idea
                    'ta_xinli' => $infoTa['me_xinli'], //另一方对于该事件此时的心理活动 ta zixun_xinli
                    'ta_wants' => $infoTa['me_work_idea'], //对方增加事件内容一 ta zixun_wants
                    //年：月：日：
                    'year_good' => implode('、', $yearGood),
                    'month_good' => implode('、', $monthGood),
                    'day_good' => implode('、', $dayGood),
                    'easy' => $easy,
                    'date1' => $historyInfo['date1'],
                    'startenddate' => implode("\n", $startenddate),//时间区间预测
                    'me_wants_date' => '我方有推进意愿的时间（年月日）' . $historyInfo['result_day'], //对方增加事件内容二  我方有推进意愿的时间（年月日）
                    'ta_xintai' => $infoTa['me_xintai'], //客方心态 ta zixun_xintai
                    'me_xintai' => $infoMe['me_xintai'], //我方的心态 zixun_xintai
                    'things_degree' => $infoMe['me_work_things_degree'], //该事件总体推进难易度 things_degree
                    'me_xinli' => $infoMe['me_xinli'], //我方对于该事件此时的心理活动 zixun_xinli
                    'rate' => $historyInfo['rate'], //指定风险管理推送频率
                    'solution' => $infoMe['cm_hope_me'], //解决方案
                    'is_show_time_res' => $historyInfo['is_show_time_res'],
                    'me_name' => empty($historyInfo['me_name']) ? '我方' : $historyInfo['me_name'],
                    'ta_name' => empty($historyInfo['ta_name']) ? '另一方' : $historyInfo['ta_name'],
                ];
                 if($historyInfo['date1']!=''){
                    $resp['me_wants_date'] = '我方有推进意愿的时间（年月日）' . $historyInfo['date1'];
                }
            }
            if ($table == 'docs_emotion') {
                $resp = [
                    'num_sn' => $infoMe['num_sn'],
                    'question_msg' => $historyInfo['person_fix_msg'],
                    'is_get_profit' => '', //我方做该事件是否可以获得利益
                    'me_wants' => $infoMe['me_tuijin'], //我方推进意愿 zixun_wants
                    'ta_idea' => '', //另一方对我的想法 ta ke_zhu_idea
                    'ta_xinli' => $infoTa['me_xinli'], //另一方对于该事件此时的心理活动 ta zixun_xinli
                    'ta_wants' => $infoTa['me_tuijin'], //对方增加事件内容一 ta zixun_wants
                    //年：月：日：
                    'year_good' => implode('、', $yearGood),
                    'month_good' => implode('、', $monthGood),
                    'day_good' => implode('、', $dayGood),
                    'easy' => $easy,
                    'date1' => $historyInfo['date1'],
                    'startenddate' => implode("\n", $startenddate),//时间区间预测
                    'me_wants_date' => '我方有推进意愿的时间（年月日）'.$historyInfo['result_day'], //对方增加事件内容二  我方有推进意愿的时间（年月日）
                    'ta_xintai' => $infoTa['me_xintai'], //客方心态 ta zixun_xintai
                    'me_xintai' => $infoMe['me_xintai'], //我方的心态 zixun_xintai
                    'things_degree' => $infoMe['me_tuijin_degree'], //该事件总体推进难易度 things_degree
                    'me_xinli' => $infoMe['me_xinli'], //我方对于该事件此时的心理活动 zixun_xinli
                    'rate' => $historyInfo['rate'], //指定风险管理推送频率
                    'solution' => $infoMe['ta_hope_me'], //解决方案
                    'is_show_time_res' => $historyInfo['is_show_time_res'],
                    'me_name' => empty($historyInfo['me_name']) ? '我方' : $historyInfo['me_name'],
                    'ta_name' => empty($historyInfo['ta_name']) ? '另一方' : $historyInfo['ta_name'],
                ];
                     if($historyInfo['date1']!=''){
                    $resp['me_wants_date'] = '我方有推进意愿的时间（年月日）' . $historyInfo['date1'];
                }
         
            }
           
            foreach ($resp as $kItem => $kVal) {
                // $resp['ta_name'] = substr_replace($resp['ta_name'], '****', 3, 4); 
                $resp[$kItem] = str_replace('\n', "\n", $resp[$kItem]);
            }

            $result_title = Db::name('result_title')->field('*')->find();
            // if($resp['ta_name']!=''){
            //       $ta_names = substr_replace($resp['ta_name'], '****', 3, 4); 
            // }else{
            //       $ta_names = ''; 
            // }

            foreach ($result_title as $kItem => $kVal) {
                $kVal = str_replace('{{me}}', $resp['me_name'], $kVal);
                $result_title[$kItem] = str_replace('{{ta}}',$resp['ta_name'], $kVal);
            }
            $resp['result_title'] = $result_title;

            $res['code'] = 0;
            $res['data'] = $resp;
            return json($res);
        } catch (\Throwable $th) {
            $res['code'] = 1;
            $res['msg'] = $th->getMessage();
            return json($res);
        }
    }

    
    
    
    
    private function _isGood($ids, array $goodIds)
    {
        if (is_array($ids)) {
            foreach ($ids as $id) {
                if (in_array($id, $goodIds)) {
                    return true;
                }
            }
            return false;
        }

        return in_array($ids, $goodIds);
    }

    private function _yuce($me, $date = '')
    {
        $tm = strtotime($date);
        $y = (int)date("Y", $tm);
        $m = (int)date("m", $tm);
        $d = (int)date("d", $tm);

        $year20 = [
            // [1944, 1963, [7, 8], 1, 0], //1944年--1963年=7和8都是
            [1964, 1983, 1, 0, 0], //1964年--1983年=1
            [1984, 2003, 2, 0, 0], //1984年--2003年=2
            [2004, 2023, 7, 0, 0], //2004年--2023年=7
            [2024, 2043, 3, 0, 0], //2024年--2043年=3
            [2044, 2063, 6, 0, 0], //2044年--2063年=6
            [2064, 2083, 8, 0, 0], //2064年--2083年=8
            [2084, 2103, 4, 0, 0], //2104年--2123年=4
            [2104, 2123, 5, 0, 0], //2104年--2123年=5
            [2124, 2143, [7, 8], 0, 0], //2124-2143=7和8都是
        ];
        //时间算法逻辑编号顺序：6～7～7a～4～5～5a～3～8～8a～2～1～1a
        $tag = ['6', '7', '7a', '4', '5', '5a', '3', '8', '8a', '2', '1', '1a'];

        $p = new paipan();
        $gz = $p->GetGZ($y, $m, $d, 0);
        $tmpYear = $gz[2]['ty'];
        $ydz = $gz[1][0];
        $mdz = $gz[1][1];
        $ddz = $gz[1][2];

        $years = [];
        $months = [];
        $days = [];
        //预测12年
        // for ($i = 0; $i < 12; $i++) {
        //     $years[] = [$tmpYear + $i, $tag[($ydz + $i) % 12], 0];
        // }
        for ($i = 0; $i < 12; $i++) {
            $idx = (($y - 2020) % 12 + $i) % 12;
            $years[] = [$y + $i, $tag[$idx], 0];
        } 
        //预测12月数据
        // for ($i = 0; $i < 12; $i++) {//干支历月份
        //     $months[] = [($m - 1 + $i) % 12 + 1, $tag[($mdz + $i) % 12], 0];
        // }
        for ($i = 0; $i < 12; $i++) { //阳历月份
            $tmpMonth = ($m - 1 + $i) % 12 + 1;
            $months[] = [$tmpMonth, $tag[$tmpMonth % 12], 0];
        }
        //预测30天数据
        for ($i = 0; $i < 30; $i++) {
            $days[] = [(int)date("d", $tm + $i * 86400), $tag[($ddz + $i) % 12], 0];
        }

        $tm = time();
        $y = date("Y", $tm);
        $m = date("m", $tm);
        $d = date("d", $tm);
        $p = new paipan();
        $gz = $p->GetGZ($y, $m, $d, 0);

        $tag = ['6', '7', '7a', '4', '5', '5a', '3', '8', '8a', '2','1', '1a'];
        $tmpYear = $gz[2]['ty'];
        $ydz = $gz[1][0];
        $mdz = $gz[1][1];
        $ddz = $gz[1][2];
        $data = [];
        for ($i = 0; $i < 12; $i++) {
            $data['years'][] = [$tmpYear + $i, $tag[($ydz + $i) % 12], 0];
        }
        for ($i = 0; $i < 12; $i++) {
            $data['months'][] = [($m - 1 + $i) % 12 + 1, $tag[($mdz + $i) % 12], 0];
        }
        for ($i = 0; $i < 30; $i++) {
            $data['days'][] = [(int)date("d", $tm + $i * 86400), $tag[($ddz + $i) % 12], 0];
        }

        $year20Good = [];
        $yearGood = [];
        $monthsGood = [];
        $daysGood = [];
        if (in_array($me, [1, 2])) {
            $year20Good = [1, 2, 6, 7, 8];
            $timeGood = ['1', '2', '8', '7', '1a', '8a', '7a'];
            $yearGood = $timeGood;
            $monthsGood = $timeGood;
            $daysGood = $timeGood;
        }
        if (in_array($me, [3])) {
            $year20Good = [3, 4, 5, 7, 8];
            $timeGood = ['4', '5', '3', '5a'];
            $yearGood = $timeGood;
            $monthsGood = $timeGood;
            $daysGood = $timeGood;
        }
        if (in_array($me, [4, 5])) {
            $year20Good = [3, 4, 5, 6];
            $timeGood = ['6', '4', '5', '5a'];
            $yearGood = $timeGood;
            $monthsGood = $timeGood;
            $daysGood = $timeGood;
        }
        if (in_array($me, [6])) {
            $year20Good = [1, 2, 4, 5, 6];
            $timeGood = ['1', '2', '6', '1a'];
            $yearGood = $timeGood;
            $monthsGood = $timeGood;
            $daysGood = $timeGood;
        }
        if (in_array($me, [7, 8])) {
            $year20Good = [1, 2, 3, 7, 8];
            $timeGood = ['7', '8', '3', '7a', '8a'];
            $yearGood = $timeGood;
            $monthsGood = $timeGood;
            $daysGood = $timeGood;
        }

        $year20GoodBad = 0;
        $yearGoodBad = 0;
        $monthGoodBad = 0;
        $dayGoodBad = 0;
        foreach ($year20 as $key => $value) {
            $year20[$key][4] = $this->_isGood($year20[$key][2], $year20Good) ? 1 : 0;
            //当前所属20年的 good bad
            if ($tmpYear >= $year20[$key][0] && $tmpYear <= $year20[$key][1]) {
                $year20GoodBad = $year20[$key][4];
            }
        }
        foreach ($years as $key => $value) {
            $years[$key][2] = $this->_isGood($years[$key][1], $yearGood) ? 1 : 0;
        }
        foreach ($months as $key => $value) {
            $months[$key][2] = $this->_isGood($months[$key][1], $monthsGood) ? 1 : 0;
        }
        foreach ($days as $key => $value) {
            $days[$key][2] = $this->_isGood($days[$key][1], $daysGood) ? 1 : 0;
        }
        $yearGoodBad = $years[0][2]; //当前年的 good bad
        $monthGoodBad = $months[0][2]; //当前月的 good bad
        $dayGoodBad = $days[0][2]; //当前日的 good bad

        return [
            'date' => $date,
            'years20' => $year20,
            'years' => $years,
            'months' => $months,
            'days' => $days,
            'year20' => $year20GoodBad,
            'ymd' => [$yearGoodBad, $monthGoodBad, $dayGoodBad],
        ];
    }


    /**
     * 获取当前用户 是否可以使用 咨询 
     */
    public function getUserIsUse()
    {
        $res = ['code' => 1, 'data' => [], 'msg' => ''];
        try {
            $cid3Map = [
                '7' => ['once' => '1', 'month' => '2', 'once_field' => 'once_nums', 'month_field' => 'month_day',],
                '8' => ['once' => '3', 'month' => '4', 'once_field' => 'works_once_nums', 'month_field' => 'works_month_nums',],
                '9' => ['once' => '5', 'month' => '6', 'once_field' => 'emotion_once_nums', 'month_field' => 'emotion_month_nums',],
                '10' => ['once' => '7', 'month' => '8', 'once_field' => 'pr_once_nums', 'month_field' => 'pr_month_nums',],
                '11' => ['once' => '9', 'month' => '10', 'once_field' => 'group_once_nums', 'month_field' => 'group_month_nums',],
                '12' => ['once' => '9', 'month' => '10', 'once_field' => 'group_once_nums', 'month_field' => 'group_month_nums',],
                '13' => ['once' => '9', 'month' => '10', 'once_field' => 'group_once_nums', 'month_field' => 'group_month_nums',],
                '14' => ['once' => '9', 'month' => '10', 'once_field' => 'group_once_nums', 'month_field' => 'group_month_nums',],
                '15' => ['once' => '9', 'month' => '10', 'once_field' => 'group_once_nums', 'month_field' => 'group_month_nums',],
                '16' => ['once' => '9', 'month' => '10', 'once_field' => 'group_once_nums', 'month_field' => 'group_month_nums',],
                '17' => ['once' => '9', 'month' => '10', 'once_field' => 'group_once_nums', 'month_field' => 'group_month_nums',],
                '18' => ['once' => '9', 'month' => '10', 'once_field' => 'group_once_nums', 'month_field' => 'group_month_nums',],
            ];
            $cid3 = input('type', ''); //获取套餐所属分类
            $user_phone = input('user_phone', '');
            if (empty($user_phone)) {
                throw new Exception("用户唯一凭证为必传标识", 1);
            }
            if (empty($cid3Map[$cid3])) {
                throw new Exception("获取会员套餐类型失败", 1);
            }
            $userInfo = Db::name('member')->field('*')->where(['phone' => $user_phone])->find();
            if (empty($userInfo)) {
                throw new Exception("获取会员信息", 1);
            }
            $vip = $cid3Map[$cid3];
            $combo_type = $vip['once'];
            $combo_type2 = $vip['month'];
            $vipKey = $vip['once_field'];
            $monthvipKey = $vip['month_field'];
            $comboInfo = Db::name('combos')->field('*')->where(['combo_type' => (int)$combo_type])->find();
            if (empty($comboInfo)) {
                throw new Exception("获取会员套餐信息失败", 1);
            }

            $freeTimes = Db::name('config')->where('id',21)->value('value');
            $res['data']['zifei'] = $comboInfo['fee']; // 获取单次付费标准
            $res['data']['times'] = $freeTimes??1; //每天免费次数
            $res['data']['is_used'] = ($userInfo[$vipKey] > 0 || $userInfo[$monthvipKey] > 0) ? 1 : 0; //有次卡数 或 包月未过期
            $res['data']['combo_type'] = $combo_type; //次卡套餐类型
            $res['data']['combo_type2'] = $combo_type2; //月卡套餐类型
            $res['code'] = 0;
            return json($res);
        } catch (\Throwable $th) {
            //throw $th;
            $res['code'] = 1;
            $res['msg'] = $th->getMessage();
            return json($res);
        }
    }
    /**
     * 调整监测预警推送频率
     */
    public function setRate()
    {
        $res = ['code' => 1, 'data' => [], 'msg' => ''];
        try {
            //code...$res['code'] = 0;
            $rate = (int)input('rate', '0');
            # 个人 咨询,历史记录
            $historyId = (int)input('history_id', '0');
            if (empty($historyId)) {
                throw new Exception(Lang::get('consultation_id_required'), 1);
            }
            # 更新订单状态
            $updateData = [
                'rate' => $rate,
            ];
            $updateRes = Db::name('new_user_question_history')->where(['id' => $historyId])->update($updateData);
            if (!$updateRes) {
                throw new Exception("更新设置失败", 1);
            }
            $res['code'] = 0;
            return json($res);
        } catch (\Throwable $th) {
            //throw $th;
            $res['code'] = 1;
            $res['msg'] = $th->getMessage();
            return json($res);
        }
    }
    //生成二维码
    public function generateQrcode(){
        //大分类
        $typeArr = [
            '7'     =>  '1-1-1',
            '8'     =>  '1-1-2',
            '9'     =>  '1-1-3',
            '10'    =>  '1-1-4',
            '11'    =>  '2-1-1',
            '12'    =>  '2-1-2',
            '13'    =>  '2-1-3',
            '14'    =>  '2-2-1',
            '15'    =>  '2-2-2',
            '16'    =>  '2-2-3',
            '17'    =>  '2-2-4',
            '18'    =>  '2-3-1',
            ];
            foreach($typeArr as $k=>$v){
                $ids = Db::name('question_new')->where(['cid3' => $k])->field('id')->select();
                foreach ($ids as $id){
                    $img = './static/qrcode/'.$k.'-'.$id['id'].'.jpg';
                    $wechatPayConf = config('app.wechat_pay');
                     # 支付平台分配给开发者的应用ID 
                    $appid = $wechatPayConf['mini_appid'];
                    # 商户API 密钥 
                    $secret = $wechatPayConf['mini_secret'];
                    $url  ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
                    $oauth2 =  json_decode(file_get_contents($url),true);
                    //TODO
                    //无限制获取小程序码，请求这个接口,scene获取不到暂时用下面的方法   
                    // $qcode ="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$oauth2['access_token'];
                    // $param = json_encode(array("page"=>"pages/result5/index","scene"=>"history_id=144650"));
                    //获取二维码 只能获取10w个 暂时用到
                    $qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=".$oauth2['access_token'];

                    $param = json_encode(array("path"=>"pages/newDetail/indexV2?type=".$typeArr[$k]."&cid3=".$k.'&qid='.$id['id'],"width"=> 430));
                    // //POST参数
                    $result = httpRequest($qcode, $param, "POST");
                   
                    // //生成二维码
                    $res = file_put_contents($img, $result); //保存服务器用到的,qrcode.png这个就是你生成的二维码图片,可以存到你指定的路径,
                }
            }
       
       
        
    }
 
    //前台文字设置
    public function gettext(){
        //首页文字
        $text = '科技部国家超算互联网联合体理事成员，国家科技成果及北京市科技成果认定，华为技术互认授权，BSIA专家库人工智能组评委开发。无明智囊[AI智囊系统]为您提供如摇号入学、考学考研等预测并提供解决方案建议。过去无可挽回，未来可以改变。
                 团体-公关(选择评估、竞标、内控、股市等自动预测)、战略-行业、战略、项目、内控等；
                 个人-项目、事业(考学、面试)、情感、公关(选择评估、股市等自动预测)。';
                 
        $text1 = '考学等结果时间明确选[是]，新年第一签选[是]，考学考研时间选[年]，其它可据需求；对方经常不回复及几乎不可能事件选[否]';         
        $text2 = '咨询事情的时间单位';     
        
        //团体用户文字
        $text3 = '无明智囊[AI智囊系统]-过去无可挽回，未来可以改变。';
        //个人用户文字
        $text4 = ' 无明智囊[AI智囊系统]-过去无可挽回，未来可以改变。';
        //团体用户--下公关维护和战略部署文字
        $text5 = '无明智囊[AI智囊系统]-过去无可挽回，未来可以改变。';
        $res['code'] = 0;
        $res['data'] = $text;
        $res['data1'] = $text1;
        $res['data2'] = $text2;
        $res['data3'] = $text3;
        $res['data4'] = $text4;
        $res['data5'] = $text5;
        return json($res);
    }
    
    
}
